﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMPLib;

namespace demo06
{
    class MediaPlayer
    {
        #region Fields
        WindowsMediaPlayer mp;
        IWMPMediaCollection media;
        #endregion

        #region Constructor
        public MediaPlayer()
        {
            this.mp = new WindowsMediaPlayer();
            this.media = mp.mediaCollection;
        }
        #endregion

        #region Methods
        #region GetInfo
        string getArtist(IWMPMedia media)
        {
            string artist = "";
            artist = media.getItemInfo("Artist");
            if (string.IsNullOrEmpty(artist))
            {
                artist = "Unknown Artist";
            }
            return artist;
        }
        string getAlbum(IWMPMedia media)
        {
            string album = "";
            album = media.getItemInfo("Album");
            if (string.IsNullOrEmpty(album))
            {
                album = "Unknown Album";
            }
            return album;
        }
        string getTitle(IWMPMedia media)
        {
            string title = "";
            title = media.getItemInfo("Title");
            if (string.IsNullOrEmpty(title))
            {
                title = media.name;
            }
            return title;
        }
        string getRating(IWMPMedia media)
        {
            string rating = media.getItemInfo("UserRating");
            if (string.IsNullOrEmpty(rating))
            {
                rating = "0";
            }
            return rating;
        }
        #endregion
        public List<MusicEntry> GetLib()
        {
            List<MusicEntry> entries;
            IWMPPlaylist medialist = null;
            IWMPMedia item;
            try
            {
                medialist = media.getByAttribute("MediaType", "Audio");
                entries = new List<MusicEntry>(medialist.count);
                for (int i = 0; i < medialist.count; i++ )
                {
                    item = medialist.get_Item(i);
                    MusicEntry entry = new MusicEntry();
                    entry.ID = i;
                    entry.Title = getTitle(item);
                    entry.Album = getAlbum(item);
                    entry.Artist = getArtist(item);
                    entry.Rating = getRating(item);
                    entry.Location = item.sourceURL;
                    entries.Add(entry);
                }
            }
            finally
            {
                if (medialist != null)
                {
                    medialist.clear();
                }
            }
            return entries;
        }
        public void Dispose()
        {
            if (mp != null)
            {
                mp.close();
            }
        }
        #endregion
    }
}
